$(function() {
    regValidate(["#bannerForm"]);
    laydate.render({
        elem: '#activeTime'
        ,type: 'datetime'
        ,range: true //或 range: '~' 来自定义分割字符
        // ,value: dateFtt("yyyy-MM-dd hh:mm:ss", preDate) + ' - ' + dateFtt("yyyy-MM-dd hh:mm:ss", curDate)
        //js赋值重置失效，改为就是怕、页面赋值
        ,isInitValue: true //是否允许填充初始值，默认为 true
    });
});

function addDept(){
    $("#deptName").val('');
    doDeptRefresh();
    $("#selectDept").modal(true);
}

function addSource(){
    $("#sourceName").val('');
    doSourceRefresh();
    $("#selectSource").modal(true);
}

function clickDept() {
    var deptList=[];
    var depts =getSelectedRows('#dataDeptTable');
    var deptCodes = getLabelNoteStr('deptOne', false);
    for (var cell in depts){
        deptList.push({value:depts[cell].deptCode,text:depts[cell].deptName});
    }
    $('#selectDept').modal('hide');
    if (deptCodes == 'ALL') {
        htmlLableByList(deptList, "deptOne");
    } else {
        addLableByList(deptList, "deptOne");
    }
}

function clickSource() {
    var sourceList=[];
    var sources =getSelectedRows('#dataSourceTable');
    var sourceCodes = getLabelNoteStr('source', false);
    for (var cell in sources){
        sourceList.push({value:sources[cell].sourceCode,text:sources[cell].sourceName});
    }
    $('#selectSource').modal('hide');
    if (sourceCodes == 'ALL') {
        htmlLableByList(sourceList, "source");
    } else {
        addLableByList(sourceList, "source");
    }
}

function doCheckImage() {
    if(!$("#bannerForm").valid()) return;//校验不通过
    if($("#bannerType").val() == 'hc_lesson_detail') {
        var deptCodes = getLabelNoteStr('deptOne', false);
        if (deptCodes == '' || deptCodes == null) {
            toastr.error("请添加对应一级科室!");
            return;
        }
    }
    if($("#bannerType").val() != 'bh_index'){
        var sourceCodes = getLabelNoteStr('source', false);
        if (sourceCodes == '' || sourceCodes == null) {
            toastr.error("请添加渠道!");
            return;
        }
    }
    if ($("#hiddenId").val() == null || $("#hiddenId").val() == '') {
         imgSrcDefault;
         var img = $('#picUrl').attr('src');
        if ((!img || img == '' || img == imgSrcDefault)) {
            toastr.error('图标不能为空');
            return false;
        }
    }
    if($("#bannerType").val() == 'hc_lesson_detail'){
        fileCheck("imgThumb", "picUrl", 60*1024, 180, 750,
            "您上传的图片大小超出限制范围（60k以内），无法上传，请重新上传符合要求的图片！",
            "您上传的图片尺寸不符合要求（750*180px），可能会影响APP展示效果，是否继续保存？",doSave);
    }
    if($("#bannerType").val() == 'hc_lesson_index'){
        fileCheck("imgThumb", "picUrl", 60*1024, 250, 500,
            "您上传的图片大小超出限制范围（60k以内），无法上传，请重新上传符合要求的图片！",
            "您上传的图片尺寸不符合要求（500*250px），可能会影响APP展示效果，是否继续保存？",doSave);
    }
    if($("#bannerType").val() == 'bh_index'){
        fileCheck("imgThumb", "picUrl", 60*1024, 180, 710,
            "您上传的图片大小超出限制范围（60k以内），无法上传，请重新上传符合要求的图片！",
            "您上传的图片尺寸不符合要求（710*180px），可能会影响APP展示效果，是否继续保存？",doSave);
    }

}

function doSave(){
    var deptListStr = getlableNote('deptOne',false).join(",");
    var sourceListStr = getLabelNoteStr('source', false);
    var id = $("#hiddenId").val();
    var data = getFromData('#bannerForm');
    var bannerType = $("#bannerType").val();
    var bannerId = $("#hiddenId").val();
    var contentType = $("#contentType").val();
    var startTime = '';
    var endTime = '';
    var picUrl = '';
    var timeInterval = $("#activeTime").val();
    if(timeInterval){
        var dates = timeInterval.split(' - ');
        if(dates && dates.length >1){
            startTime = dates[0];
            endTime = dates[1];
        }
    }
    if(judgementDate(startTime,endTime) <= 0){
        toastr.error('开始时间必须小于结束时间 ');
        return;
    }
    if($("#bannerType").val() != 'hc_lesson_detail') {
        contentType = '';
    }
    var sortNum = (!data.sortNum || data.sortNum == '') ? 999 : data.sortNum;
    var postData = {
        id : id,
        bannerId : bannerId,
        title : data.title,
        bannerType : bannerType,
        contentType : contentType,
        startTimeStr : startTime,
        endTimeStr : endTime,
        shortName : data.shortName,
        linkUrl : data.linkUrl,
        sortNum : sortNum,
        picUrl : picUrl,
        deptCodes : deptListStr,
        sourceCodeListStr : sourceListStr
    };
    var url;
    if(id == null || id == ''){
        url = basePath + 'operative/banner/addBanner';
    }else{
        url = basePath + 'operative/banner/editBanner';
    }
    $.ajaxFileUpload({
        type: 'post',
        url: url,
        dataType: 'json',
        secureuri : false,
        fileElementId : ["imgThumb"],
        contentType : "application/json; charset=UTF-8",
        data: postData,
        success : function (data) {
            hideLoading();
            if (data.result) {
                toastr.success(data.message);
                doBack();
                return;
            }else{
                toastr.error(data.message);
                return;
            }
        },
        error: function (request) {
            hideLoading();
            delayToastr('系统错误');
        }
    });
}

function doCheckDataChange() {
    var id = $("#hiddenId").val();
    var deptListStr = getlableNote('deptOne',false).join(",");
    var timeInterval = $("#activeTime").val();
    var data = getFromData('#bannerForm');
    var bannerType = $("#bannerType").val();
    var contentType = $("#contentType").val();
    if($("#bannerType").val() == 'hc_lesson_detail' && contentType == undefined){
        contentType = 'undefined';
    }
    if($("#bannerType").val() == 'hc_lesson_index') {
        contentType = null;
        deptListStr = null;
    }
    if(id == null || id == ''){
        contentType = null;
        deptListStr = null;
    }
    var postData = {
        title : data.title,
        bannerType : bannerType,
        contentType : contentType,
        shortName : data.shortName,
        activeTime : timeInterval,
        linkUrl : data.linkUrl,
        sortNum : data.sortNum,
        deptCodes : deptListStr
    };
    if (!Compare(postData,bannerDto)) {
        swalClosePageToastr(doBack);
        return;
    }
    doBack();
}

function doBack(){
    var bannerType = searchInfo.bannerType;
    if(bannerType == 'undefined'){
        bannerType = '';
    }
    window.location.href = basePath + 'operative/banner/bannerPage?title='+searchInfo.title+'&deptCode='+searchInfo.deptCode
        +'&status='+searchInfo.status+'&bannerType='+bannerType+'&t=' + new Date().getTime();
}


function doDeptRefresh(){
    var deptName = $.trim($("#deptName").val());
    $('#dataDeptTable').bootstrapTable('refresh', {
        url: basePath + 'operative/banner/findDeptList?deptName='+deptName+'&t='+new Date().getTime(),
    });
}

function doSourceRefresh(){
    var sourceName = $.trim($("#sourceName").val());
    $('#dataSourceTable').bootstrapTable('refresh', {
        url: basePath + 'operative/banner/findSourceList?sourceName='+sourceName+'&t='+new Date().getTime(),
    });
}

function getParams(params) {
    var deptListStr = getlableNote('deptOne',false).join(",");
    if(deptListStr == ','){
        deptListStr = '';
    }
    var sourceListStr = getlableNote('source',false).join(",");
    if(sourceListStr == ','){
        sourceListStr = '';
    }
    var postData = {
        deptListStr : deptListStr,
        sourceListStr : sourceListStr,
        pageSize : params.pageSize,
        pageNo : params.pageNumber
    };
    return postData;
}